package com.ktkj.init.dto.validator;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

/**
 * 字符串日期格式验证
 *
 * @author ktkj
 */
public class DateStringFormatValidator implements ConstraintValidator<DateStringFormat, String> {
    private DateStringFormat dateStringFormat;

    @Override
    public void initialize(DateStringFormat dateStringFormat) {
        this.dateStringFormat = dateStringFormat;

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(value)) {
            return true;
        }
        String format = dateStringFormat.format();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            simpleDateFormat.parse(value.trim());
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
